const fs = require("fs");
const path = require("path");
const UPLOADENUMS = {"WAITTING": 0, "UPLOADING_CYCLE": 1, "UPLOADING_IMG": 2};
const {execSync} = require("child_process");
const iOSFormats = [
    'PVRTC1_2',
    'PVRTC1_4',
    'ASTC_4x4',
    // 'ASTC_6x6',
    'ASTC_8x8',
    'ASTC_10x10',
    'ASTC_12x12' 
];
const AndroidFormats = [
    'ETC1',
    'ETC2',
    'ASTC_4x4',
    // 'ASTC_6x6',
    'ASTC_8x8',
    'ASTC_10x10',
    'ASTC_12x12' 
];
const etcQualitys = [

    'etcfast',
    'etcnormal',
    'etcslow'
];
const pvrQualitys = [

    'pvrtcfastest',
    'pvrtcfast',
    'pvrtclow',
    'pvrtcnormal',
    'pvrtchigh',
    'pvrtcveryhigh',
    'pvrtcthorough',
    'pvrtcbest'
];
const astcQualitys = [

    'astcveryfast',
    'astcfast',
    'astcmedium',
    'astcthorough',
    'astcexhaustive'
];
const getExtension = (format) => {
    let ext = '';
    if (format.includes('PVR')) {
        ext = 'pvr';
    } else if (format.includes('ETC')) {
        ext = 'ktx';
    } else if (format.includes('ASTC')) {
        ext = 'ktx';
    }
    return ext;
}
// function deleteall(path, excludeList = []) {
// 	var files = [];
// 	if(fs.existsSync(path)) {
// 		files = fs.readdirSync(path);
// 		files.forEach(function(file, index) {
// 			var curPath = path + "/" + file;
//             if (excludeList && excludeList.includes(curPath)) {

//             } else { 
//                 if(fs.statSync(curPath).isDirectory()) { // recurse
//                     deleteall(curPath);
//                 } else { // delete file
//                     fs.unlinkSync(curPath);
//                 }
//             }
// 		});
//         if (excludeList && excludeList.includes(path)) {

//         } else { 
//             fs.rmdirSync(path);
//         }
// 	}
// }; 
function colorLog(color, str) {
    if (color) { 
        if (color == 'yellow') {
            color = 'orange';
        }
        // console.log(colors(color, str));
        console.log( '%c' + str, `color:${color};`);
    } else { 
        console.log(str);
    }
}
class Tool {
    constructor() {}
 
 
    // 构建html file对象，供上传时使用
    getFile(filePath) {
        if (!filePath) {
            throw new Error(`getFile 参数不全: ${filePath}`);
        }
        let canUse = true;
        if (!canUse) { // 通知调用者，调用不成功
            throw new Error("函数不能被调用，没有通过 isToolCanUse() 验证");
        }

        const encoding = null;
        let  
            _fileName = path.basename(filePath),
            extname = path.extname(_fileName),
            type;
        switch(extname) {
            case ".zip":
                type = "application/zip";
                break;
            case ".jpg":
                type = "image/jpeg";
                break;
            case ".png":
                type = "image/png";
                break;
            case ".mp3":
                type = "audio/mp3";
                break;
            case ".wav":
                type = "audio/wav";
                break;
            case ".ttf":
                type = "application/octet-stream";
                break;
            default:
                type = "";
        }
        let buffer = fs.readFileSync(filePath, encoding); 
        let file = new File([buffer], _fileName, {type: type});
        return file;
    }

  
    /**
     * 获取图片的宽高
     * - 传过来的是HTML file对象
     */
    getImageWH(sourceImgPath) {

        
        let _file = codeMain.tool.getFile(sourceImgPath);

        return codeMain.tool.getImageWH(_file); 
    }
 
 
}
function execCmd(cmd, okFun, errFun) {

    var option;
    option={encoding:"binary",maxBuffer:1024*1024*20};
    
    var exec = require('child_process').exec;
    var job = exec(cmd,function(err,stdOut,stdErr){ 
        if (err){ 
            errFun(stdErr);
            // throw new Error(`执行失败： stdErr ${stdErr}  cmd ${cmd}`); 
        }
        else{ 
            okFun(stdOut);
        }
    
    },option);
    window.pvrToolcurrJob = job;
    window.pvrToolJobs = window.pvrToolJobs || [];
    window.pvrToolJobs.push(job);
  }
let proName = "PVRTexToolCLI";
function  timeoutToKill(obj) {
    // window.timeoutToKillList = window.timeoutToKillList || [];
    if (obj.job.exitCode !== 0) {
        _timeoutToKill(obj);
    }
}
function  _timeoutToKill(obj) {
    var option ={encoding:"binary",maxBuffer:1024*1024*120}; 
    if (process.platform === "win32") { 
        let cmdList = `tasklist | findstr ${proName}.exe`; 
        try {

            var str = execSync(cmdList, option);
            let proList = str.split('\n');
            let pidList = [];
            for(let i = 0; i < proList.length; i++) {
                let line = proList[i]; 
                let result = line.match(/PVRTexToolCLI.exe\s*(.\d+?)\s/);
                if (result) {
                    let pid = result[1];
                    pidList.push(pid);
                    obj.job.kill(0);
                    obj.isTimeout = true;
                    let cmd = `chcp 65001 && taskkill /pid ${pid}  -t  -f`;
                    let res = execSync(cmd, option);
                    console.log(`kill ${pid} -> ${res}`); 
                }
            }
        } catch(e) {
            console.log('try to kill PVRTexToolCLI fail:', e);
        }
        // console.log('timeoutToKill', str);
    }  
}
function doSpawn(cmd, obj,okFun, errFun) { 
    var option ={encoding:"binary",maxBuffer:1024*1024*120}; 
    const spawn = require('child_process').spawn
    option.shell = true;
    // option.cwd = cwd;
    if (window.pvrToolcurrJob) {
      window.pvrToolcurrJob.kill(0);
      let index2= window.pvrToolJobs.indexOf(window.pvrToolcurrJob);
      if (index2 >=0) {
        window.pvrToolJobs.splice(index2, 1);
      }
      window.pvrToolcurrJob = null;
    }
    const job = spawn(cmd, option);
    let dataStr = '';
    let errorStr = '';
    let stderrStr = '';
    job.stdout.on('data', (data) => {
        console.log(`stdout ${data}`);
        dataStr += `${data}`;
    });
    job.on('error', (data) => {
      stderrStr  += `${data}`;
  
      errFun && errFun(errorStr || stderrStr);   

        colorLog('red', `${cmd} exit error  ` )
    });
    window.pvrToolcurrJob = job;
    window.pvrToolJobs = window.pvrToolJobs || [];
    window.pvrToolJobs.push(job);
    // job.on('exit', (data) => {
    //     // console.log(`exit ${data}`);
    // });
    job.stderr.on('data', (data) => {
      console.log(`stderr ${data}`);
      //   console.log(`stderr data: ${data}`); 
        // console.log("Error Occured: "+data); 	
        dataStr += `${data}`;	
        stderrStr  += `${data}`;	
    });
  
    job.on('close', (code) => {  
        if (code ==0) {
            // console.log("end",  code, 'cmd', cmd);  
            okFun && okFun(dataStr);
        } else {
          //   throw new Error(`执行失败： code ${code}  cmd ${cmd} --`);
            errFun && errFun(errorStr || stderrStr);   
        } 
        if (code != 0) {
            if (obj && obj.isTimeout) { 
                colorLog('yellow', `${cmd} timeOut ... will retry  ` )
            } else { 
                colorLog('red', `${cmd} exit code ${code}  ` )
            }
        }
    }); 
    return job;
  } 
 
 
let PVRTexToolDir = '';
let PVRTexToolFile = '';

class MyTool   { 

    constructor() {
        this.tool = new Tool();
        this.qList = [];
        this.qId = 100000;
        this.queue = {};
        this.fs = fs;
        this.path = path;
        
    }
    mkdirsSync(dirname, mode) {
        if (this.fs.existsSync(dirname)) {
            return true;
        } else {
            if (this.mkdirsSync(this.path.dirname(dirname), mode)) {
                this.fs.mkdirSync(dirname, mode);
                return true;
            }
        }
    }
    getResult(queue_id, callback) {
        
        let uploadReObj = this.queue[queue_id]; 
        if (uploadReObj && (uploadReObj.status === 0 || uploadReObj.status === 2)) {
            
            callback(null, {statusCode: 200},uploadReObj);
        } else {
            if (uploadReObj.status == -1) {
                uploadReObj.status = -2;
                this.compress(queue_id);
            }
            callback('notReady', {statusCode: 200},uploadReObj);
        }

    }
    compress(queue_id) {

        let uploadReObj = this.queue[queue_id]; 
        let info = uploadReObj.info;
        let toolpath =  PVRTexToolFile;
        // let tmp = path.join(PVRTexToolDir, 'tmp', queue_id  + '.' + info.extension );
        let __index = info.file.lastIndexOf('.');
        let tmp = info.file.substring(0, __index + 1) + info.extension ;
        tmp = tmp.replace(info.sourceImgDirPath, info.destImgDirPath);
        let tmpDir = '';
        let index_ = tmp.lastIndexOf('/');
        if (index_ == -1) {
            index_ = tmp.lastIndexOf('\\');
        }
        tmpDir = tmp.substring(0, index_);
        if (!fs.existsSync(tmpDir)) {
            myTool.mkdirsSync(tmpDir)
        }
        let cmd = `"${toolpath}"  -i "${info.file}" -f ${info.format} ${info.other} -o "${tmp}"  `; 
         colorLog("yellow", cmd);
         let args = [`-i ${info.file}"`,`-f ${info.format}`];
         args = args.concat(info.otherList);
         args.push(`-o "${tmp}" `);
         let cwd = path.join(toolpath, '../');
        //  execCmd (cmd , () => { 
        let job = doSpawn(cmd , uploadReObj, () => { 
            // doExecFile(toolpath,[' -help "flip"'] ,  () => { 
            uploadReObj.status = 0;
            uploadReObj.data.fileName = tmp; 
            clearTimeout(uploadReObj.timerId);

        }, (str) => {
            if (uploadReObj.isTimeout) {
                uploadReObj.isTimeout = false;
                uploadReObj.status = -1; 
                uploadReObj.job = null;
            } else { 
                uploadReObj.status = 2; 
                uploadReObj.error = str; 
                uploadReObj.job = null;
            }
            clearTimeout(uploadReObj.timerId);
        });

        // mac 没有长时间挂起的问题，不需要这么做
        if (process.platform !== 'darwin') { 
            if (!uploadReObj.timeOutValue) {
                uploadReObj.timeOutValue = 1000 * 15;
            } else { 
                uploadReObj.timeOutValue += 1000 * 8;
                if (uploadReObj.timeOutValue > 1000 * 60 * 5) {
                    uploadReObj.timeOutValue = 1000 * 60 * 5;
                }
            }
            uploadReObj.job = job;
            uploadReObj.timerId = setTimeout(() => {
                timeoutToKill(uploadReObj);
            }, uploadReObj.timeOutValue); 
        } 
    }
    exChange(info, callback) {
        // console.log('info', info);
        // this.qList.push(info);
        this.qId ++;
        let uploadReObj = {
            ret: 0,
            msg:"OK",
            data: {
                queue_id: this.qId,
                fileName: info.file
            },
            info: info,
            status: -1
        } 
        this.queue[this.qId] = uploadReObj;
        callback(null, {statusCode: 200},uploadReObj);
    }
    //面板的语言包
    getPanelLang(index) {
        return codeMain.getPanelLang(index);
    }
    walk(_path, arrList, prefix) {
        // let tmp = path.join(PVRTexToolDir, 'tmp'); 
        // myTool.mkdirsSync(tmp);
        // deleteall(tmp,[tmp])
        var files = myTool.fs.readdirSync(_path);
        files.forEach((item) => {
            var tmpPath = path.join(_path, item);
            var stats = myTool.fs.statSync(tmpPath);
            let 
                pathRelative,
                pathObj;
            if (stats.isDirectory()) {
                this.walk(tmpPath, arrList, prefix);
            } else {
                pathRelative = path.relative(prefix, tmpPath);
                if (process.platform === "win32" || process.platform === "win64") {
                    pathRelative = pathRelative.replace(/\\/g, "/");
                }
                pathObj = {"url": pathRelative};
                arrList.push(pathObj);
            }
        });
    }
}
let myTool = new MyTool();
class TextureExchange {
    constructor() {
        
    }

    resetVariable() {
        this.allFileList = []; // 所有的待转换图片
        this.uploadIndex = 0; // 上传的图片在allFileList中的index
        this.finishFileObj = {}; // 转换后的图片
        this.waitDownFileObj = {}; // 已上传，等待下载纹理图片
        this.uploadStatus = UPLOADENUMS.WAITTING; // 上传图片状态 {0: 等待上传, 1: 进入上传周期, 2: 正在上传图片}
        this.isDownloading = false; // 正在下载图片
        this.stopLoop = false;
    }

    /**
     * 显示panel-纹理
     */
    showExchangeImg() {
        // PVRTexToolDir D:\work\new\layaairide2\resources\app\out\vs\layaEditor\h5\js
        PVRTexToolDir = path.join(__dirname, '../../libs/PVRTexTool')
        console.log('PVRTexToolDir', __dirname, PVRTexToolDir);
        
        PVRTexToolFile =  path.join( PVRTexToolDir,
    process.platform   == 'darwin' ? 'OSX_x86/PVRTexToolCLI' : 'Windows_x86_64/PVRTexToolCLI.exe'); 
        this.resetVariable();
        // 判断会员
        let isVIP = codeMain.checkVIP();
        if (!isVIP) {
            return;
        }
        // 创建背景容器
        this.requestTexturePanel = getElement("div", "common-whole-wrapper");
        this.requestTexturePanel.id = "requestTexture";
        this.requestTexturePanel.style.zIndex = 199999999;
        this.requestTexturePanel.innerHTML = `
            <div class="common-main-wrapper" style="width: 600px; height: 530px;">
                <div class="common-tool-title">
                    <div class="common-tool-icon-wrapper">
                        <img class="common-tool-icon" title="${codeMain.getPanelLang(470)}" src="skins/default/image/ide/layamaker-newpro.png" style="width: 18px; height: 20px;">
                    </div>
                    <div class="common-tool-title-content">${codeMain.getPanelLang(470)}</div>
                    <div class="common-tool-close"></div>
                </div>
                <div class="upload-mian-area">
                    <!-- 错误显示 -->
                    <div class="common-error-prompt" style="display: none; z-index: 2;">
                        <div class="common-error-circle"></div>
                        <div class="common-error-prompt-content"></div>
                    </div>
                    <!-- 图片路径 -->
                    <span class="common-inputbefore-label" style="position: absolute; width: 65px; left: 10px; text-align: right; top: 100px;">${codeMain.getPanelLang(468)}</span>
                    <input class="common-skins-input upload-file-input" type="text" placeholder="${codeMain.getPanelLang(468)}" style="left: 100px; width: 380px; top: 100px;"/>
                    <button class="common-skins-file-btn upload-file-btn" type="text" style="top: 100px; left: 510px;">${codeMain.getPanelLang(22)}</button>
                    <div style="position: absolute; left: 100px; text-align: right; top: 130px;">${codeMain.getPanelLang(525)}</div>
                    <div style="position: absolute; left: 100px; text-align: right; top: 150px;">${codeMain.getPanelLang(526)}</div>
                    <!-- 保存路径 -->
                    <span class="common-inputbefore-label" style="position: absolute; width: 65px; left: 10px; text-align: right; top: 180px;">${codeMain.getPanelLang(469)}</span>
                    <input class="common-skins-input download-file-input" type="text" placeholder="${codeMain.getPanelLang(469)}" style="left: 100px; width: 380px; top: 180px;" readonly="readonly"/>
                    <button class="common-skins-file-btn download-file-btn" type="text" style="top: 180px; left: 510px;">${codeMain.getPanelLang(22)}</button>
                    <!-- 使用平台 -->
                    <span class="common-inputbefore-label" style="position: absolute; width: 65px; left: 10px; text-align: right; top: 220px;">${codeMain.getPanelLang(478)}</span>
                    <select class="use-platform" style="position: absolute; width: 100px; left: 100px; text-align: right; top: 220px;">
                        <option>Android</option>
                        <option>iOS</option>
                    </select> 
                    <!-- 格式  -->
                    <span class="common-inputbefore-label" style="position: absolute; width: 65px; left: 10px; text-align: right; top: 250px;">${codeMain.getPanelLang(622)}</span>
                    <select id="tex_format" class="tex_format" style="position: absolute; width: 100px; left: 100px; text-align: right; top: 250px;" disabled="disabled">
                         <option selected>ETC1</option> 
                    </select>
                    <!-- 质量 -->
                    <span class="common-inputbefore-label" style="position: absolute; width: 65px; left: 10px; text-align: right; top: 280px;">${codeMain.getPanelLang(623)}</span>
                    <select class="pvr-quality" style="position: absolute; width: 100px; left: 100px; text-align: right; top: 280px;" disabled="disabled">
                        <option selected>pvrtcfast</option> 
                    </select>
                    <!-- 预乘 -->
                    <label style="position: absolute; left: 64px; top: 310px; color: #5c91f1; font-size: 16px; color: #CCCCCC;">
                        <input id="isAlpha" type="checkbox" checked="checked" > <span style="margin-left: 18px;">${codeMain.getPanelLang(624)}</span>
                    </label> 
                    <!-- minmap   --> 
                    <label style="position: absolute; left: 64px; top: 340px; color: #5c91f1; font-size: 16px; color: #CCCCCC;">
                        <input id="isMipmap" type="checkbox" checked="checked" > <span style="margin-left: 18px;">MIPMaps</span>
                    </label>
                    <div style="position: absolute; left: 100px; top: 370px; color: #5c91f1;">
                    <!-- <div style="top: 250px; color: #5c91f1; width: 460px;">${codeMain.getPanelLang(527)}</div>-->
                        <div style="top: 270px; color: #5c91f1; width: 460px;">${codeMain.getPanelLang(528)}</div>
                        <div style="top: 270px; color: #5c91f1; width: 460px;">${codeMain.getPanelLang(529)}</div>
                    </div> 
                    <input class="common-skins-input PVRTexToolFileDiv" type="text"  value=${PVRTexToolFile} style="display:none;left: 100px; width: 380px; top: 420px;"/>
                    <!-- 确定按钮 -->
                    <button class="common-skins-ok-btn" style="top: 470px; left: 250px;">${codeMain.getPanelLang(38)}</button>
                </div>
            </div>
        `;
        codeMain.addPopLayer(this.requestTexturePanel);
        let 
            title = this.requestTexturePanel.getElementsByClassName("common-tool-title")[0];
        __Layadrag(this.requestTexturePanel, title);
        this.bindRequestTextureEvent();
        this.textureVIPRegLogin();
    }

    bindRequestTextureEvent() {
        let 
            uploadFileInput = this.requestTexturePanel.getElementsByClassName("upload-file-input")[0],
            downFileInput = this.requestTexturePanel.getElementsByClassName("download-file-input")[0],
            errorPanel = this.requestTexturePanel.getElementsByClassName("common-error-prompt")[0];

        // let PVRTexToolFileDiv = this.requestTexturePanel.getElementsByClassName("PVRTexToolFileDiv")[0]; 
       

        let oldInfo = localStorage.getItem("textureInput");
        if (oldInfo) {
            try {
                oldInfo = oldInfo && JSON.parse(oldInfo);
                uploadFileInput.value = oldInfo.input;
                downFileInput.value = oldInfo.output;
                // PVRTexToolFileDiv.value = 
            } catch(e) {}
        }

        this.requestTexturePanel.addEventListener('click', () => {
            let target = event.target;
            let parentNodeEle = target;
            for (let i = 0; i < 10; i++) {
                if (!parentNodeEle) { // 没有父元素了，return
                    return;
                }
                let className = parentNodeEle.className;
                if (typeof className !== "string") {
                    return;
                }
                if (className.indexOf('common-main-wrapper') !== -1) {
                    return;
                }
                if (className == 'common-skins-ok-btn') { // 确定
                    this.requestTextureOK();
                    return;
                } else if (className.includes("upload-file-btn")) { // 资源btn
                    errorPanel.style.display = "none";
                    codeMain.remote.dialog.showOpenDialog({
                        properties: ["openFile", "openDirectory"],
                        filters: [{name: 'image', extensions: ["jpg", "png", "json", "atlas"]}],
                        defaultPath: uploadFileInput.value
                    }, function(p) {
                        if (p) {
                            uploadFileInput.value = p[0];
                        }
                    });
                } else if (className.includes("download-file-input") || className.includes("download-file-btn")) { // 下载路径btn
                    errorPanel.style.display = "none";
                    codeMain.remote.dialog.showOpenDialog({
                        properties: ["openDirectory", 'createDirectory'],
                        defaultPath: downFileInput.value
                    }, function(p) {
                        if (p) {
                            downFileInput.value = p[0];
                        }
                    });
                }
                parentNodeEle = parentNodeEle.parentNode;
            }
        }, false);
        // drop事件
        this.requestTexturePanel.addEventListener('drop', (e) => {
            e.preventDefault();
            errorPanel.style.display = "none";
            let filePath = e.dataTransfer.files[0].path;
            let r = fs.lstatSync(filePath);
            if (r.isFile() && (filePath.endsWith(".png") || filePath.endsWith(".jpg") || filePath.endsWith(".json") || filePath.endsWith(".atlas"))) {
                uploadFileInput.value = filePath;
            } else if (r.isDirectory()) {
                uploadFileInput.value = filePath;
            }
        });
        // 关闭按钮
        this.requestTexturePanel.getElementsByClassName("common-tool-close")[0].addEventListener("click", () => {
            codeMain.removePopLayer(this.requestTexturePanel);
            this.stopLoop = true;
            clearTimeout(this.uploadFileTimout);
            clearTimeout(this.textureChangeLoopTimout); 
        }, false);
        let usePlatformEle = this.requestTexturePanel.getElementsByClassName("use-platform")[0];
        let pvrQualityEle = this.requestTexturePanel.getElementsByClassName("pvr-quality")[0]; 
        let tex_formatEle = this.requestTexturePanel.getElementsByClassName("tex_format")[0]; 
        
        const changeQualityOptions = (_format = '') => {
            let list = [];  
            if (_format.includes('ETC')) {
                list = etcQualitys;
            } else if (_format.includes('PVR')) {
                list = pvrQualitys;
            } else if (_format.includes('ASTC')) {
                list = astcQualitys;
            }
            let _html = '';
            for (let i = 0, len = list.length; i < len; i++) {
                let quality = list[i]; 
                if (i == 0) {
                    pvrQualityEle.value = `${quality}`;
                }
                _html += `<option value="${quality}">${quality}</option>`;
            }
            pvrQualityEle.innerHTML = _html;
        }
        const changeFormatOptions = (_platform) => {
            let list = _platform == 'iOS' ? iOSFormats : AndroidFormats;  
            let _html = '';
            for (let i = 0, len = list.length; i < len; i++) {
                let format = list[i]; 
                if (i == 0) {
                    tex_formatEle.value = `${format}`;
                    changeQualityOptions(format);
                }
                _html += `<option value="${format}">${format}</option>`;
            }
            tex_formatEle.innerHTML = _html;
        }
        // let isAlphaEle = document.getElementById("isAlpha");
        // let isMipmapEle = document.getElementById("isMipmap"); 
        usePlatformEle.addEventListener("change", () => {
            // if (usePlatformEle.value === "iOS") {
            //     // pvrQualityEle.disabled = false;
            //     isAlphaEle.disabled = false;
            // } else {
            //     // pvrQualityEle.disabled = true;
            //     isAlphaEle.disabled = true;
            // }
            changeFormatOptions(usePlatformEle.value);
        })
        tex_formatEle.addEventListener("change", () => { 
            changeQualityOptions(tex_formatEle.value);
        })
        
        tex_formatEle.disabled = false;
        pvrQualityEle.disabled = false;
        
        let texture_exchange_config = localStorage.getItem("texture_exchange_config");  
        // JSON.stringify({ isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap,isScalePic}
        if (texture_exchange_config) {
            texture_exchange_config = JSON.parse(texture_exchange_config);
            let  
            usePlatform = this.requestTexturePanel.getElementsByClassName("use-platform")[0],
            pvrQualityEle = this.requestTexturePanel.getElementsByClassName("pvr-quality")[0], 
            tex_formatEle = this.requestTexturePanel.getElementsByClassName("tex_format")[0], 
            isAlphaEle = document.getElementById("isAlpha"),
            isMipmapEle = document.getElementById("isMipmap");
            // isScalePicEle = document.getElementById("isScalePic");
            usePlatform.value = texture_exchange_config.isAndroid ? 'Android' : 'iOS';
            changeFormatOptions(usePlatform.value);
            tex_formatEle.value = texture_exchange_config.texformatEle;  
            changeQualityOptions(tex_formatEle.value);
            pvrQualityEle.value = texture_exchange_config.pvrQuality; 
            isAlphaEle.checked = texture_exchange_config.isAlpha;
            isMipmapEle.checked = texture_exchange_config.isMipmap;

        } else { 
            changeFormatOptions('Android');
        }
        // 检测是否登录过，如果没有登录，强制其登录
        let loginInfo = codeMain.layaPageIns.getLoginInfo();
        if (!loginInfo) {
            let params = {
                show: true,
            };
            codeMain.layaPageIns.createLayaLoginHTML(params);
        }
    }

    /**
     * 检测是否是VIP，如果是VIP，则重新登录
     * - 在执行的过程中，一旦后台返回token失效，不再自动登录
     */
    textureVIPRegLogin() {
        let loginInfo = codeMain.layaPageIns.getLoginInfo();
        if (loginInfo && loginInfo.is_vip === 1) {
            // 添加loading效果
            let loaderEle = document.createElement("div");
            loaderEle.id = "loader";
            loaderEle.style.display = "flex";
            loaderEle.innerHTML = `
                <div class="load-container load4">
                    <div class="loader">Loading...</div>
                </div>
            `;
            if (this.requestTexturePanel) {
                this.requestTexturePanel.appendChild(loaderEle);
            }
            // 重新登录
            sessionStorage.removeItem("getMasterTokenTime");
            codeMain.regLogin(true, () => {
                let loadingEle = document.getElementById("loader");
                loadingEle && loadingEle.remove();
            });
            return;
        }
    }

    /**
     * 执行纹理转换
     */
    requestTextureOK() {
        this.resetVariable();
        let 
            uploadFileInput = this.requestTexturePanel.getElementsByClassName("upload-file-input")[0],
            downFileInput = this.requestTexturePanel.getElementsByClassName("download-file-input")[0],
            usePlatform = this.requestTexturePanel.getElementsByClassName("use-platform")[0],
            pvrQualityEle = this.requestTexturePanel.getElementsByClassName("pvr-quality")[0], 
            tex_formatEle = this.requestTexturePanel.getElementsByClassName("tex_format")[0], 
            isAlphaEle = document.getElementById("isAlpha"),
            isMipmapEle = document.getElementById("isMipmap"), 
            isScalePicEle = document.getElementById("isScalePic"), 
            
            errorPanel = this.requestTexturePanel.getElementsByClassName("common-error-prompt")[0],
            errorInfo = this.requestTexturePanel.getElementsByClassName("common-error-prompt-content")[0];
        let 
            sourceImgDirPath = uploadFileInput.value,
            destImgDirPath = downFileInput.value;
        let 
            isAndroid = usePlatform.selectedIndex === 0;
        let pvrQuality = pvrQualityEle.value;
        let texformatEle = tex_formatEle.value;
        let isAlpha = isAlphaEle.checked;
        let isMipmap = isMipmapEle ? isMipmapEle.checked : true; 
        let isScalePic = isScalePicEle ? isScalePicEle.checked : true; 
        // 判断是不是会员
        let loginInfo = codeMain.layaPageIns.getLoginInfo();
        if (!loginInfo || loginInfo.is_vip !== 1) {
            errorPanel.style.display = "block";
            errorInfo.innerText = codeMain.getPanelLang(489); // 该功能是VIP专属功能，如果您已经充值VIP，请重新登录以刷新状态
            return;
        }
        if (!sourceImgDirPath || !destImgDirPath) {
            errorPanel.style.display = "block";
            errorInfo.innerText = codeMain.getPanelLang(471); // 图片路径和保存路径不可为空
            return;
        } else if (!fs.existsSync(sourceImgDirPath) || !fs.existsSync(destImgDirPath)) {
            errorPanel.style.display = "block";
            errorInfo.innerText = codeMain.getPanelLang(472); // 图片路径或保存路径不存在
            return;
        }
        localStorage.setItem("textureInput", JSON.stringify({input: sourceImgDirPath, output: destImgDirPath}));

        // 添加loading效果
        let loaderEle = document.createElement("div");
        loaderEle.id = "loader";
        loaderEle.style.display = "flex";
        loaderEle.innerHTML = `
            <div class="load-container load4">
                <div class="loader">Loading...</div>
            </div>
        `;
        if (this.requestTexturePanel) {
            this.requestTexturePanel.appendChild(loaderEle);
        }

        // 如果是一个文件夹，逐个进行纹理压缩
        // 全部当成一个文件夹处理
        let r = fs.lstatSync(sourceImgDirPath);
        if (r.isFile()) { // 文件
            this.allFileList = [sourceImgDirPath];
        } else if (r.isDirectory()) { // 文件夹
            let dirname = path.dirname(sourceImgDirPath);
            let fileObjList = [];
            codeMain.walk(sourceImgDirPath, fileObjList, dirname);
            for (let i = 0, len = fileObjList.length; i < len; i++) {
                this.allFileList[i] = path.join(dirname, fileObjList[i].url);
            }
        }

        console.groupEnd();
        console.group();

        this.stopLoop = false;
        this.textureChangeLoop(sourceImgDirPath, destImgDirPath, isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap,isScalePic); 

        
        localStorage.setItem("texture_exchange_config", JSON.stringify({ isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap,isScalePic}));
    }

    /**
     * 执行纹理转换
     */
     work(program,__dir) {
        // (program.input, program.output, program.platform, program.format, program.quality , program.premultiplyAlpha );

        this.resetVariable(); 
             
        let 
            sourceImgDirPath =  path.isAbsolute(program.input) ? program.input : path.join(__dir, program.input),
            destImgDirPath = path.isAbsolute(program.output) ? program.output : path.join(__dir, program.output);
        let 
            isAndroid = program.platform === 'Android';
        let pvrQuality = program.quality;
        let texformatEle = program.format;
        let isAlpha = program.premultiplyAlpha;
        let isMipmap =  program.mipmaps;
        let alphaBleed =  program.alphaBleed; 
        
        let isScalePic =  true;  
        if (!sourceImgDirPath || !destImgDirPath) {
            console.log(myTool.getPanelLang(471)) ; // 图片路径和保存路径不可为空
            return;
        } else if (!myTool.fs.existsSync(sourceImgDirPath) || !myTool.fs.existsSync(destImgDirPath)) {
            console.log(myTool.getPanelLang(472)); // 图片路径或保存路径不存在
            return;
        }
        localStorage.setItem("textureInput", JSON.stringify({input: sourceImgDirPath, output: destImgDirPath}));

   
        // 如果是一个文件夹，逐个进行纹理压缩
        // 全部当成一个文件夹处理
        let r = myTool.fs.lstatSync(sourceImgDirPath);
        if (r.isFile()) { // 文件
            this.allFileList = [sourceImgDirPath];
        } else if (r.isDirectory()) { // 文件夹
            let dirname = path.dirname(sourceImgDirPath);
            let fileObjList = [];
            myTool.walk(sourceImgDirPath, fileObjList, dirname);
            for (let i = 0, len = fileObjList.length; i < len; i++) {
                this.allFileList[i] = path.join(dirname, fileObjList[i].url);
            }
        }

        console.groupEnd();
        console.group();

        this.stopLoop = false;
        this.textureChangeLoop(sourceImgDirPath, destImgDirPath, isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap,isScalePic, alphaBleed); 
    }

    textureChangeLoop(sourceImgDirPath, destImgDirPath, isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap,isScalePic,alphaBleed) {
        if (this.stopLoop) {
            console.groupEnd();
            return;
        } 
        let 
        errorPanel = this.requestTexturePanel.getElementsByClassName("common-error-prompt")[0],
        errorInfo = this.requestTexturePanel.getElementsByClassName("common-error-prompt-content")[0];
        let 
            totalLen = this.allFileList.length,
            finishLen = Object.keys(this.finishFileObj).length;
        
        if (this.uploadIndexOld !=  this.uploadIndex || this.finishLenOld != finishLen) {
            this.finishLen = finishLen;
            (colorLog('blue', `loop --> totalLen: ${totalLen} uploadIndex: ${this.uploadIndex} finishLen: ${finishLen}`)); 
        }
        if (finishLen >= totalLen) { // 所有文件执行完成
            if (totalLen > 1) {
                // console.log(myTool.getPanelLang(495)); // 纹理压缩结束，请在控制台查看单个文件是否成功
                errorPanel.style.display = "block";
                errorInfo.innerText = codeMain.getPanelLang(495); // 纹理压缩结束，请在控制台查看单个文件是否成功
            } 
            console.groupEnd(); 
            // let tmp = path.join(PVRTexToolDir, 'tmp');  
            // deleteall(tmp);
            console.log("纹理压缩结束: ");
            let ks = Object.keys(this.finishFileObj);
            for(let i= 0; i < ks.length; i ++) {
                let k = ks[i]; 
                let info = this.finishFileObj[k];
                if (info.isSuccess) { 
                    console.log( `  ${k}  %c${info.text}`, 'color: green;');
                } else { 
                    
                    if(info.notImg) {
                        console.log( ` ${k} %c ${info.text}`, 'color: orange;'); 
                    } else {  
                        console.log( ` ${k} %c ${info.text}`, 'color: red;'); 
                    }
                }
            }
            console.groupEnd();
            // console.log('this.finishFileObj', this.finishFileObj);
            let loadingEle = document.getElementById("loader");
            loadingEle && loadingEle.remove();
            return;
        }

        // 分为两部分，上传和下载
        let params = {
            sourceImgDirPath,
            destImgDirPath,
            isAndroid,
            pvrQuality,
            isAlpha,
            texformatEle,
            isMipmap,
            isScalePic,
            alphaBleed

        };
        // 1) 如果还有待上传的资源，则进入请求上传分支
        if (this.uploadIndex !== totalLen) {
            this.uploadFileToServer(params, (infoObj) => {
                let 
                    text = infoObj.text,
                    stopLoop = infoObj.stopLoop,
                    needRecord = infoObj.needRecord,
                    isSuccess = infoObj.isSuccess,
                    sourceImgPath = infoObj.sourceImgPath;

                if (!infoObj.notImg)   {
                    errorPanel.style.display = "block";
                    errorInfo.innerText = `${path.basename(sourceImgPath)}: ${text}`;
                    console.log(`${path.basename(sourceImgPath)}: ${text}`);
                }
                if (!!stopLoop) { 
                    this.stopLoop = true;
                    return;
                }
                if (needRecord) { // 特殊的，图片在上传过程中被打回，也要标记为已完成
                    this.finishFileObj[sourceImgPath] = {
                        isSuccess: isSuccess,
                        text: text,
                        notImg: infoObj.notImg
                    }
                }
            });
        }
        // 2) 如果已经有上传的资源了，则进入请求下载分支
        if (this.uploadIndex !== 0) {
            this.downFileFromServer(params, (infoObj) => {
                let 
                    isSuccess = infoObj.isSuccess,
                    text = infoObj.text,
                    sourceImgPath = infoObj.sourceImgPath,
                    queue_id = infoObj.queue_id;
                    if (isSuccess) { 
                        (colorLog('green', `${path.basename(sourceImgPath)}: ${text}`));
                    } else { 
                        if (infoObj.notImg) { 
                            (colorLog('yellow', `${path.basename(sourceImgPath)}: ${text}`));
                        } else { 
                            (colorLog('red', `${path.basename(sourceImgPath)}: ${text}`));
                        }
                    }
                    
                    errorPanel.style.display = "block";
                    errorInfo.innerText = `${path.basename(sourceImgPath)}: ${text}`;

                delete this.waitDownFileObj[queue_id];
                this.isDownloading = false;
                this.finishFileObj[sourceImgPath] = {
                    isSuccess: isSuccess, 
                    text: text
                };
            });
        }
        // 每 10s 循环一次
        this.textureChangeLoopTimout = setTimeout(() => {
            this.textureChangeLoop(sourceImgDirPath, destImgDirPath, isAndroid, pvrQuality, isAlpha, texformatEle, isMipmap, isScalePic,alphaBleed);
        }, 1001);
    }

    uploadFileToServer(params, cbfunc) {
        // console.log('this.uploadStatus !== UPLOADENUMS.WAITTING', this.uploadStatus , UPLOADENUMS.WAITTING);
        if (this.uploadStatus !== UPLOADENUMS.WAITTING) {
            return;
        }
        // (colorLog("blue", "count (uploadFileToServer) begin..."));
        this.uploadStatus = UPLOADENUMS.UPLOADING_CYCLE;

        return    this.uploadFile(params, 1, cbfunc); 
    }

    uploadFile(params, canUpImgCount, cbfunc) {
        
        let doNext = (delayCall) =>{
            this.uploadStatus = UPLOADENUMS.UPLOADING_CYCLE;
            clearTimeout(this.uploadFileTimout);
            if (delayCall) { 
                this.uploadFileTimout = setTimeout(() => {
                    this.uploadFile(params, 100000000 , cbfunc);
                }, 1000);
            } else {
                
                this.uploadFile(params, 100000000 , cbfunc);
            }
            // this.uploadFile(params, 100000000 , cbfunc);
        }
        if (canUpImgCount <= 0 || this.uploadIndex >= this.allFileList.length || this.uploadStatus == UPLOADENUMS.UPLOADING_IMG) {
            return;
        }
        this.uploadStatus = UPLOADENUMS.UPLOADING_IMG;
        let { isAndroid, pvrQuality, isAlpha, texformatEle,isMipmap ,isScalePic,alphaBleed, sourceImgDirPath, destImgDirPath} = params;
        let sourceImgPath = this.allFileList[this.uploadIndex];
        this.uploadIndex++;
        // (colorLog('',` exchange_queue (uploadFile) begin: ${sourceImgPath}`) );

        let 
            extension = path.extname(sourceImgPath),
            fileName = path.basename(sourceImgPath);

        if (![".jpg", ".jpeg", ".png"].includes(extension)) {
            cbfunc({isSuccess: false, needRecord: true, sourceImgPath: sourceImgPath, notImg: true, text: myTool.getPanelLang(494)}); // 图片文件不是jpg和png格式
            doNext.call(this, false);
            return;
        }
        if (isAndroid && texformatEle == 'ETC1' && ![".jpg", ".jpeg"].includes(extension)) {
            cbfunc({isSuccess: false, needRecord: true, sourceImgPath: sourceImgPath, notImg: true, text: myTool.getPanelLang(473)}); // Android平台ETC1格式只可以上传jpg格式图片
            doNext.call(this, false);
            return;
        }

        // 上传图片 
        myTool.tool.getImageWH(sourceImgPath).then(({width, height}) => {
            let _sideWidth = width;
            // Android平台，长宽可以不相等，但都必须为2的幂次方
            if (extension != ".png") {
                isAlpha = false;
            }
            let mipmapStr = isMipmap ? `-m ` : '';
            let p2 = isMipmap;
            if (texformatEle.includes("ETC2") || texformatEle.includes("ASTC")) { 
                // 4的倍数
                if (!Number.isInteger(width/4)) {
                    width = Math.ceil(width/4) *4;
                } 
                if (!Number.isInteger(height/4)) {
                    height = Math.ceil(height/4) *4;
                } 
            }
            if (isAndroid) {
                if (texformatEle.includes("ETC1")) {
                    p2 = true;
                }


            }
            if (p2) { 
                if (!Number.isInteger(Math.log2(width))) {
                    let _log2 = Math.ceil(Math.log2(width));
                    width = Math.pow(2, _log2);
                }
                if (!Number.isInteger(Math.log2(height))) {
                    let _log2 = Math.ceil(Math.log2(height));
                    height = Math.pow(2, _log2);
                }
            }
            _sideWidth = width > height ? width : height;
            // iOS平台，或者astc格式图片像素长宽相等，必须为2的幂次方
            if (!isAndroid && !texformatEle.includes("ASTC")) {
                let longerSide = width > height ? width : height;
                let _log2 = Math.ceil(Math.log2(longerSide));
                width = height = _sideWidth = Math.pow(2, _log2);
            }
            // 获取纹理图片的幂次方(Android长宽是否为2的幂次方，在这里判断)
            // let mipmap = Math.log2(_sideWidth) + 1;

            // 获取请求参数
            let 
                _format,
                _extension,
                _other;
            
            let quality = `-q ${pvrQuality}`;
            let ics = '';  
            let useCanvas = isScalePic  ? 'canvas' : '';
            let useAlphaBleed = alphaBleed  ? '-l' : '';
            let resize =   `-r${useCanvas} ${width},${height}`;
            // isMipmap = false;// 默认
            // let mipmapStr = isMipmap ? `-m ${mipmap}` : '';
            let otherList = [];
            const addOther = (arg) => {
                if (arg) {
                    otherList.push(arg);
                }
            }
            if (isAndroid) {
                _format = texformatEle;//"ETC1";  
                if ('ETC2' == _format) {  
                    if (extension != ".png") {
                        _format = _format + '_RGB';
                    } else { 
                        _format = _format + '_RGBA';
                    }
                    ics = '-ics lRGB';
                } else if(_format.includes('ASTC')){ 
                    ics = '-ics lRGB';
                } else {
                    isAlpha = false;
                    useAlphaBleed = '';
                    ics = '-ics lRGB';
                }
                let premultiplyAlpha = isAlpha ? "-p" : "";
                _extension = getExtension(texformatEle);//"ktx";
                _other = `  ${useAlphaBleed}   ${mipmapStr} ${resize}  ${premultiplyAlpha} ${quality} ${ics}`;// " -m " + 图片mipmap.ToString() + "-q etcfast "
                addOther(useAlphaBleed);
                addOther(mipmapStr);
                addOther(resize);
                addOther(premultiplyAlpha);
                addOther(quality);
                addOther(ics);
            } else {
                _extension = getExtension(texformatEle);// "pvr";
                _format = texformatEle;
                if ('pvr' == _extension) { 
                    if (extension != ".png") {
                        _format = _format + '_RGB';
                    } 
                    ics = '-ics lRGB';
                } else if(_format.includes('ASTC')){ 
                    ics = '-ics lRGB'; 
                } 
                // -p 预乘 
                let premultiplyAlpha = isAlpha ? "-p" : "";
                _other = ` ${useAlphaBleed} ${mipmapStr} ${resize} ${premultiplyAlpha} ${quality}  ${ics}`; // " -m " + 图片mipmap.ToString() + " -r "+ 图片像素大小.ToString()+ "," + 图片像素大小.ToString()+ " -q pvrtcfastest ";
                addOther(useAlphaBleed);
                addOther(mipmapStr);
                addOther(resize);
                addOther(premultiplyAlpha);
                addOther(quality);
                addOther(ics);
            }
            // console.error(_other);
            var formData = {
                file: sourceImgPath,
                sourceImgDirPath: sourceImgDirPath,
                destImgDirPath: destImgDirPath,
                format: _format,
                extension: _extension, 
                other: _other,  
                otherList: otherList,  
            };
            // console.log(formData);
            // return;
            myTool.exChange(formData, (error, response, body) => { 
                // (colorLog('blue',`exchange_queue complete ${sourceImgPath} ↓`) );
                error && console.error(error);
                // console.log(`${body}`);

                if (error) {
                    cbfunc({isSuccess: false, needRecord: true, sourceImgPath: sourceImgPath, text: error});
                    doNext.call(this);
                    return;
                }
                if (response.statusCode == 200) {
                    let uploadReObj = body;// JSON.parse(`${body}`);
                    if (uploadReObj.ret !== 0) {
                        cbfunc({isSuccess: false, needRecord: true, sourceImgPath: sourceImgPath, text: uploadReObj.msg});
                        doNext.call(this);
                        return;
                    } 
                    this.waitDownFileObj[uploadReObj.data.queue_id] = {
                        serverFileName: uploadReObj.data.fileName,
                        fileName: fileName,
                        sourceImgPath: sourceImgPath
                    };

                    doNext.call(this);
                }
            }); 
        }).catch((e) => {
            // console.log(` exchange_queue catch.error: ${sourceImgPath}`, "color: #FF0080;");
            console.error(e);

            cbfunc({isSuccess: false, needRecord: true, sourceImgPath: sourceImgPath, text: myTool.getPanelLang(476)}); // 未知错误，请与服务提供商联系
            doNext();
        });

    }

    downFileFromServer(params, recordListFunc) { 
        if (this.isDownloading) {
            return;
        }
        let keys = Object.keys(this.waitDownFileObj); 
        if (keys.length == 0) {
            return;
        }
        this.isDownloading = true;
        let { sourceImgDirPath, destImgDirPath, isAndroid, texformatEle } = params;

        let queue_id = keys[0];
        let serverFileName = this.waitDownFileObj[queue_id].serverFileName;
        let fileName = this.waitDownFileObj[queue_id].fileName;
        let sourceImgPath =this.waitDownFileObj[queue_id].sourceImgPath;
        // console.log(` get_exchange_file (downFileFromServer) begin: ${sourceImgPath}`, "color: #009100;");

        if (this.uploadIndexOld !=  this.uploadIndex || this.finishLenOld != this.finishLen) {
            this.uploadIndexOld = this.uploadIndex;
            this.finishLenOld = this.finishLen;
            // console.log(` get_exchange_file (downFileFromServer) begin: ${sourceImgPath}` );
        }

        let 
            extension = path.extname(sourceImgPath);

        myTool.getResult(queue_id,  
            (error, response, body) => {
                if (error == 'notReady') {
                    this.isDownloading = false;
                    return;
                } 
                colorLog('blue',`get_exchange_file complete ${sourceImgPath} ↓` );
                error && console.error(error);
                // console.log(`${body}`);

                if (error) {
                    recordListFunc({isSuccess: false, sourceImgPath: sourceImgPath, text: error,  queue_id: queue_id });
                    throw error;
                }
                if (response.statusCode == 200) {
                    let downloadImgReObj = body;
                    // console.log(downloadImgReObj);
                    this.isDownloading = false;
                    if (downloadImgReObj && downloadImgReObj.msg) {
                        if (downloadImgReObj.status === 2) {
                            // 失败了
                            let errorTxt = myTool.getPanelLang(621);//`压缩纹理失败，请尝试更改压缩格式`;
                            recordListFunc({isSuccess: false, sourceImgPath: sourceImgPath, text: errorTxt + downloadImgReObj.error,  queue_id: queue_id });
                            return
                        }
                    } 
                    console.log("开始下载二进制纹理...");
                    let reExtension = "." + downloadImgReObj.info.extension; //  isAndroid ? ".ktx" : ".pvr";
                    // 保持目录结构
                    let _relativePath;
                    if (path.dirname(sourceImgDirPath) !== path.dirname(sourceImgPath)) { // 当传入的是文件夹时，两者不相等
                        _relativePath = path.relative(sourceImgDirPath, path.dirname(sourceImgPath));
                    }
                    let destImgDirRePath = destImgDirPath;
                    if (_relativePath) {
                        destImgDirRePath = path.join(destImgDirPath, _relativePath);
                    }
                    if (!myTool.fs.existsSync(destImgDirRePath)) {
                        // console.log('destImgDirRePath', destImgDirRePath);
                        myTool.mkdirsSync(destImgDirRePath);
                    }
                    let reFileNamePng = path.join(destImgDirRePath, fileName); 
                    let reFileName = path.join(destImgDirRePath, fileName.replace(extension, "") + reExtension);
                    // myTool.fs.writeFileSync(reFileName, body, "binary");
                    console.log('reFileName', reFileName);
                    // fs.copyFileSync(downloadImgReObj.data.fileName, reFileName);
                     
                    if (sourceImgPath.endsWith("png")) { // 如果是图集，则改变atlas(json)文件
                        let 
                            atlasPath = sourceImgPath.replace(/(\.png)$/, ".atlas"),
                            jsonPath = sourceImgPath.replace(/(\.png)$/, ".json");
                        let _atlasPath;
                        let _atlasPathDest;

                        if (myTool.fs.existsSync(atlasPath)) {
                            _atlasPath = atlasPath;
                            _atlasPathDest = reFileNamePng.replace(/(\.png)$/, ".atlas");
                        } else if (myTool.fs.existsSync(jsonPath)) {
                            _atlasPath = jsonPath;
                            _atlasPathDest = reFileNamePng.replace(/(\.png)$/, ".json");
                        }
                        if (_atlasPath) {
                            
                            try {
                                let content = myTool.fs.readFileSync(_atlasPath, "utf8");
                                let atlasJson = JSON.parse(content);
                                // 两个平台都转过则两个都启用压缩纹理
                                delete atlasJson.meta.compressTextureAndroid; 
                                delete atlasJson.meta.compressTextureIOS;
                                delete atlasJson.meta.astc;
                                delete atlasJson.meta.etc;
                                delete atlasJson.meta.pvr;
                                if (isAndroid) {
                                    atlasJson.meta.compressTextureAndroid = true; 
                                } else { 
                                    atlasJson.meta.compressTextureIOS = true;
                                }
                                let astc = texformatEle.includes('ASTC');
                                let etc = texformatEle.includes('ETC');
                                let pvr = texformatEle.includes('PVR');
                                if (astc) {
                                    atlasJson.meta.astc = true; 
                                } else if(etc) { 
                                    atlasJson.meta.etc = true;
                                } else if(pvr) { 
                                    atlasJson.meta.pvr = true;
                                }
                                if (_atlasPath === _atlasPathDest) { 
                                    myTool.fs.writeFileSync(_atlasPath, JSON.stringify(atlasJson), "utf8");
                                } else { 
                                    myTool.fs.writeFileSync(_atlasPathDest, JSON.stringify(atlasJson), "utf8");
                                }
                                
                            } catch(e) {}
                        }
                    }

                    recordListFunc({isSuccess: true, sourceImgPath: sourceImgPath, text: myTool.getPanelLang(477), queue_id: queue_id}); // 纹理图片转换成功
                }
            });
    }
 
}

let textureExchange = new TextureExchange();
module.exports = textureExchange;
